package com.whz.governance.monitor;

import com.google.common.base.Stopwatch;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.lang.NonNull;

import java.util.concurrent.TimeUnit;

/**
 * @author whz
 */
@Slf4j
@Aspect
public class TimeCostMonitorAopBean {

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.whz.governance.monitor.TimeCostMonitor)" +
              "||@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void monitor() {
    }

    @Around("monitor()")
    @SneakyThrows
    public Object surroundInform(@NonNull ProceedingJoinPoint proceedingJoinPoint) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        String signature = proceedingJoinPoint.getSignature().toShortString();
        try {
            return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        } finally {
            long consumeTime = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
            log.info("[{}]:COST-TIME:{} ms", signature, consumeTime);
        }
    }
}